package servlet;


import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import pojo.Student;
import service.StuService;
import service.serviceImpl.StuServiceImpl;
;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class StuServlet extends BaseServlet {

    public String stuLogin(HttpServletRequest request, HttpServletResponse response)  {
        try {
            //获得用户输入的账号,密码
            String id = request.getParameter("name");
            String pwd = request.getParameter("password");

            //调用业务层
            StuService stuService = new StuServiceImpl();
            Student  stu = stuService.findStuById(id,true);

            if(stu != null && pwd.equals(stu.getStu_pwd())){
                //账号和密码都正确
                request.getSession().setAttribute("stu", stu);
                return "/jsp/stuInfo.jsp";
            }
            request.getSession().setAttribute("loginMsg","账号或密码输入有误");
        } catch (Exception e) {
            request.getSession().setAttribute("loginMsg","账号或密码输入有误");
        }
        return "/jsp/stuLogin.jsp";
    }

    public void findStuById(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id");
            //调用业务层
            StuService stuService = new StuServiceImpl();

            Student stu =  stuService.findStuById(id,false);
            //将查找到的学生转换成JSON格式返回给页面
            JSONObject jObj = JSONObject.fromObject(stu);
            String strJson = jObj.toString();
            response.getWriter().write(strJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public  void updateStu(HttpServletRequest request, HttpServletResponse response){
        try {
            //接受前台传过来的参数，由于传的个数太多，直接封装到map中
            Map<String, String []> map = request.getParameterMap();

            //遍历map
//            for (String key : map.keySet()) {
//                for (String str:map.get(key)) {
//                    System.out.println(key + "==" + str);
//                }
//            }

            //创建一个新的对象，这个对象保存了用户修改的信息，需要更新到数据库
            Student stu = new Student();
            BeanUtils.populate(stu,map);
//          System.out.print(stu.toString());

            //调用业务层更新学生
           StuService stuService = new StuServiceImpl();
           stuService.updateStu(stu);
           //修改成功，返回信息给页面
           response.getWriter().write("1");
        } catch ( Exception  e) {
            e.printStackTrace();
        }
    }
}